//
//  YDBMessageViewController.swift
//  DKE-Album
//
//  Created by 杨东宝 on 2018/8/8.
//  Copyright © 2018年 杨东宝. All rights reserved.
//

import UIKit
import Toast_Swift
import EmptyDataSet_Swift
class YDBDeiviceViewController: YDBBaseViewController {
    var deviceList:[DeviceModel]?
    var selectScreen:Screen?
    var scan:YDBScanViewController?
    //MARK: - 提示文案
    lazy var tipLab: UILabel = {
        let lab = UILabel.init()
        lab.text = String(format: "\("total_device".localized) 0 \("device_total".localized)")
        lab.textColor = HexRGB(0x8B8C8D)
        lab.font = DIMENSION_FONT_OF_SIZE(14)
        view.addSubview(lab)
        return lab
    }()
    //MARK: - 提示文案
    lazy var floatBtn: DraggableFloatingButton = {
        let lab = DraggableFloatingButton()
        view.addSubview(lab)
        return lab
    }()
    //MARK: - 扫描按钮
    lazy var rightBtn:UIButton = {
        let messageBtn = UIButton.init(type: .custom)
        messageBtn.setImage(imageNamed("add_service"), for: .normal)
        messageBtn.size = CGSize(width: DIMENSION_VALUE(30), height: DIMENSION_VALUE(30))
        messageBtn.addTarget(self, action: #selector(deviceScanBtnClick(_ : )), for: .touchUpInside)
        return messageBtn
    }()
    //MARK: - 已选择尺寸按钮
    lazy var selectedLab: UILabel = {
        let lab = UILabel.init()
        lab.text = "no_select".localized
        lab.textColor = HexRGB(0x8B8C8D)
        lab.font = DIMENSION_FONT_OF_SIZE(14)
        lab.numberOfLines = 0
        view.addSubview(lab)
        return lab
    }()
    //MARK: - 切换尺寸按钮
    lazy var selectScreenBtn:UIButton = {
        let messageBtn = UIButton.init(type: .custom)
        messageBtn.setTitle("screen_size".localized, for: .normal)
        messageBtn.layer.masksToBounds = true
        messageBtn.layer.cornerRadius = DIMENSION_VALUE(15)
        messageBtn.backgroundColor = HexRGB(0x3d4466)
        messageBtn.setTitleColor(.white, for: .normal)
        messageBtn.titleLabel?.font = DIMENSION_FONT_OF_SIZE(12)
        messageBtn.addTarget(self, action: #selector(showSelectionDialog(_ : )), for: .touchUpInside)
        if #available(iOS 15.0, *) {
            var configuration = UIButton.Configuration.plain()
            configuration.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10)
            messageBtn.configuration = configuration
        } else {
            messageBtn.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
        }
        messageBtn.sizeToFit()
        view.addSubview(messageBtn)
        return messageBtn
    }()
    override func viewDidLoad() {
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBtn)
        super.viewDidLoad()
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        setTitle()
        addNavigationItems(titles: ["transferMode".localized], isLeft: true, target: self, action: #selector(jumpTransmissionMode(_ :)), tags: [1000])
        setFrames()
        guard let screenType = userManger.curUserInfo?.screenType else {
            showScreen(selectedIndex: 1)
            return
        }
        showScreen(selectedIndex: screenType)
    }
    func setTitle(){
        if let transmissionMode = userManger.curUserInfo?.transmissionMode {
            if transmissionMode == 1 {
                self.navigationItem.title = "wifi".localized
            }else{
                self.navigationItem.title = "bluetooth".localized
            }
        }else{
            self.navigationItem.title = "wifi"
        }
    }
    @objc func jumpTransmissionMode(_ btn:UIButton) {
        // 创建弹窗
        let dialog = SelectionDialogView(
            title: "selectBtn".localized,
            items: toTransModeArray(),
            selectedIndex: nil
        ){ selectedIndex in
            userManger.curUserInfo?.transmissionMode = selectedIndex
            userManger.saveUserInfor()
            self.setTitle()
            self.setupLoadData()
        }
        // 显示弹窗
        dialog.show()
    }
    func setFrames() {
        tipLab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
            make.top.equalToSuperview().offset(DIMENSION_VALUE(5))
            make.height.equalTo(DIMENSION_VALUE(30))
        }
        selectScreenBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
            make.top.equalTo(tipLab.snp_bottom).offset(DIMENSION_VALUE(5))
            make.height.equalTo(DIMENSION_VALUE(30))
        }
        selectedLab.snp.makeConstraints { make in
            make.left.equalTo(selectScreenBtn.snp_right).offset(DIMENSION_VALUE(5))
            make.centerY.equalTo(selectScreenBtn.snp_centerY)
            make.right.equalTo(view.snp_right).offset(DIMENSION_VALUE(-5))
            make.height.equalTo(DIMENSION_VALUE(50))
        }
        view.addSubview(tableView)
        tableView.register(DeviceListCell.self, forCellReuseIdentifier: "DeviceListCell")
        tableView.myh_footer?.isHidden = true
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(selectedLab.snp_bottom)
        }
        self.floatBtn.snp.makeConstraints { make in
            make.right.equalTo(view.snp_right).offset(DIMENSION_VALUE(-10))
            make.bottom.equalTo(view.snp_bottom).offset(DIMENSION_VALUE(-10))
            make.width.height.equalTo(60)
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setupLoadData()
    }
    override func setupLoadData() {
        deviceList =  userManger.getDeviceList(isWifi: userManger.curUserInfo?.transmissionMode == 1 ? true:false)
        tipLab.text = String(format: "\("total_device".localized) \(deviceList?.count ?? 0) \("device_total".localized)")
        tableView.myh_header?.endRefreshing()
        tableView.reloadData()
    }
}
extension YDBDeiviceViewController{

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  deviceList?.count ?? 0
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell : DeviceListCell = tableView.dequeueReusableCell(withIdentifier: "DeviceListCell") as! DeviceListCell
        cell.model = deviceList![indexPath.row]
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if selectScreen == nil {
            view.showToastCenter(message: "screen_name".localized)
            return
        }
        let deviceModel = deviceList![indexPath.row]
        if #available(iOS 12.0, *) {
            if userManger.curUserInfo?.transmissionMode == 1 {
                didClick(ssid: deviceModel.name,bssid: deviceModel.ID)
              return
            }
            let detailVC = YDBDetailViewController()
            detailVC.selectScreen = selectScreen
            detailVC.deviceModel = deviceModel
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
}

extension YDBDeiviceViewController:YDBScanViewControllerDelegate{
    //MARK: - 扫描按钮点击
    @objc func deviceScanBtnClick(_ btn:UIButton) {
        if selectScreen == nil {
            view.showToastCenter(message: "screen_name".localized)
            return
        }
        if userManger.curUserInfo?.transmissionMode == 1 {
            if #available(iOS 12.0, *) {
                didClick()
            } else {
                // Fallback on earlier versions
            }
          return
        }
        scan =  YDBScanViewController()
        scan?.delegate = self
        self.navigationController?.pushViewController(scan!, animated: true)
    }
    //MARK: - 扫描页面回调
    func didSelectDevice(deviceModel: DeviceModel) {
        scan?.navigationController?.popViewController(animated: false)
        scan = nil
        if #available(iOS 12.0, *) {
            let detailVC = YDBDetailViewController()
            detailVC.selectScreen = selectScreen
            detailVC.deviceModel = deviceModel
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
}
extension YDBDeiviceViewController{
    //MARK: - 切换设备尺寸点击事件
    @objc func showSelectionDialog(_ btn:UIButton) {
        // 创建弹窗
        let dialog = SelectionDialogView(
            title: "selectBtn".localized,
            items: toNameArray(),
            selectedIndex: nil
        ){ selectedIndex in
            print("选择了第\(selectedIndex + 1)个选项")
            self.showScreen(selectedIndex: selectedIndex)
        }
        // 显示弹窗
        dialog.show()
    }
    func showScreen(selectedIndex:Int){
        userManger.curUserInfo?.screenType = selectedIndex
        userManger.saveUserInfor()
        self.selectScreen = screenArray[selectedIndex]
        var isYehuo = false
        switch self.selectScreen?.screenType {
        case .ELECTRONICALBUM_2530_BW:fallthrough
        case .ELECTRONICALBUM_2530_E6:fallthrough
        case .ELECTRONICALBUM_2800_E6:fallthrough
        case .ELECTRONICALBUM_3120_BW:fallthrough
        case .ELECTRONICALBUM_4200_BW:
            isYehuo = true
        default:
            isYehuo = false
        }
        if userManger.curUserInfo?.transmissionMode == 0 && isYehuo{
            AlertManager.shared.showConfirm(title: "tips".localized, message: "confirmTip6".localized,confirmAction:  { [self] in
                userManger.curUserInfo?.transmissionMode = 1
                userManger.saveUserInfor()
                self.setTitle()
                self.setupLoadData()
            })
        }
       self.selectedLab.text =  String(format: "\(self.selectScreen?.name ?? "")")
    }
}
@available(iOS 12.0, *)
extension YDBDeiviceViewController:EmptyDataSetSource,EmptyDataSetDelegate{
    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        
        let normalString = "暂无可使用的设备，点击可设置"
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 18),
            .foregroundColor: UIColor.gray
        ]
        let attributedString = NSAttributedString(string: normalString, attributes: attributes)
        return attributedString

    }
    func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? {
        return imageNamed("noOrderIcon")
    }

    func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) {
        didClick()
    }
    func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) {
        didClick()
    }
    func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
        return DIMENSION_VALUE(-75)
    }
    func didClick(ssid:String? = nil,bssid:String? = nil) {
        if userManger.curUserInfo?.transmissionMode == 1 {
            //确定了当前连接的wifi与设备的wifi一致
            guard let wifiInfo = WiFiHelper.getCurrentSSID() else {
                AlertManager.shared.showConfirm(title: "tips".localized, message: "device_list_tip2".localized,confirmTitle: "去设置",cancelTitle: "取消",confirmAction:  {
                    if #available(iOS 13.0.0, *) {
                        self.jumpSetting()
                    }
                }) {}
                return
            }
            if (ssid != nil) && (bssid != nil){
                if ssid != wifiInfo.ssid && bssid != wifiInfo.bssid{
                    AlertManager.shared.showConfirm(title: "tips".localized, message: "device_list_tip3".localized,confirmTitle: "去设置",cancelTitle: "取消",confirmAction:  {
                        if #available(iOS 13.0.0, *) {
                            self.jumpSetting()
                        }
                    }){}
                }else{
                    let detailVC = YDBDetailViewController()
                    detailVC.selectScreen = self.selectScreen
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }
            }else{
                AlertManager.shared.showConfirm(title: "tips".localized, message: "device_list_tip1".localized,confirmTitle: "确定一致",cancelTitle: "去设置",confirmAction:  {
                        let detailVC = YDBDetailViewController()
                        detailVC.selectScreen = self.selectScreen
                        self.navigationController?.pushViewController(detailVC, animated: true)
                    
                    let deviceModel = DeviceModel(isWifi:true,name: wifiInfo.ssid,ID: wifiInfo.bssid)
                    userManger.addDeviceModel(deviceModel: deviceModel)
                }) {
                    if #available(iOS 13.0.0, *) {
                        self.jumpSetting()
                    }
                }
            }
            return
        }
        //如果是蓝牙直接进入扫描页面
        deviceScanBtnClick(rightBtn)
    }
    func jumpSetting() {
        // 获取系统设置页面的 URL
        if let url = URL(string: "App-Prefs:root=WIFI"), UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
}
